import { Component, OnInit} from '@angular/core';
import { NavController, NavParams,AlertController,ModalController,LoadingController,Loading } from 'ionic-angular';
import { ChoosePointsPage } from '../choose-points/choose-points';
import { Mistake } from '../mistake';
import {Events} from "ionic-angular";
import { MistakeService } from '../mistake.service';
import { SameExamplePage } from '../same-example/same-example';
import { QuestionSetPage } from '../question-set/question-set';
import { Http, Response,Headers,RequestOptions } from "@angular/http";
import { SubstituteQuestionPage } from "../substitute-question/substitute-question";
import {LoginNewService} from "../../log-in/login-new.service";


@Component({
    selector: 'page-temp-edit-mistake',
    templateUrl: 'temp-edit-mistake.html',
    providers:[MistakeService],

  })
  export class TempEditMistakesPage implements OnInit{
      subject:string;//添加错题的课程
      username:string;//用户名
      currentPoint:string="point1";
      tempPointList:string[];
      pointListReturned:string[];
      tempContent:string ="";
      tempPoint:string ="";
      tempPointFlag:boolean = false;
      mistakeListByPoints: Mistake[];
      editFlag:boolean;
      editStr:string = "edit";
      substituteFlag:boolean = false;
      substituteButtonFlag:boolean = false;
      quesItemFlag :boolean = true;
      id:string;
      starnum = 3;
      flag:boolean;
      course:string = "语文";
      pointsSelected;
      source = " ";
      starList : string[];
      blingStarPath : string;
      darkStarPath : string;
      focus : number;
      public currentDate: String;
      //public chosenDate: String;
      testCheckboxOpen: boolean;
      testCheckboxResult;
      mistake1: Mistake;
      imgflag:number = 0;
      picImgFlag:number = 0;
      quesPiclist:Array<{path:string,flag:boolean}>;
      answerPiclist:Array<{path:string,flag:boolean}>;
      substituteQuestion:any;
      substituteQuesList:any;
      hasChooseQuestion:boolean = false;//是否选中题目，选中则显示题目详细信息
      substituteQuestionChosen:any;//根据搜题之后资源库中选中的题目
      substitutePointList:any;
      searchByText:string;
      pictureOrText:string="";

       //add at 2017-12-17
       private uploadBaseUrl = ' http://118.89.157.80:8080/app/uploadBase64';
       public token:string;

      constructor(public navCtrl: NavController,
                  public alertCtrl: AlertController,
                  public modalCtrl: ModalController,
                  public mistakeService: MistakeService,
                  public navparams:NavParams,
                  public loadingCtrl: LoadingController,
                  public event:Events,
                  public logService:LoginNewService
                 ){
        this.subject = this.navparams.get("subject");
        console.log("添加错题页面："+this.subject);
        this.username= this.navparams.get("username");
        this.currentPoint = this.navparams.get("currentPoint");
        this.currentDate = this.getDate2();
        //this.chosenDate = this.currentDate;
        this.source = " ";
        this.blingStarPath = "assets/icon/star.png";
        this.darkStarPath = "assets/icon/star-2.png";
        this.starList = [];
        this.pointsSelected = [];

        this.quesPiclist = [];
        this.answerPiclist = [];
        this.pointListReturned = [];
        this.substituteQuestion = [];
        this.substituteQuesList = [];
        this.substitutePointList = [];
        this.substituteQuestionChosen = "";
        this.searchByText = "";
        this.tempPointList=[];

        this.focus = 0;
        this.id = this.getDate2()+"";
        this.mistake1 = new Mistake("12345",null,"233","233","point119","233","233","233","233","233","233","","","");
        this.mistake1.misId = this.id;
        this.mistake1.points = "456"

        for(let i = 0;i < 5;i++){
          this.starList.push(this.darkStarPath);
        }

      }


      ngOnInit():void{

      }


      changeStatus(){
        console.log(this.editFlag);
        console.log(this.editStr);
        if(this.editFlag == false){
          this.editFlag = true;
          this.editStr = "complete";
        }else if(this.editFlag == true){
          this.editStr = "edit"
          this.editFlag = false;
        }else{
          this.editFlag = true;
          this.editStr = "complete";
        }
      }

      //知识点
      presentModal() {

          let modal = this.modalCtrl.create(ChoosePointsPage,{});
          modal.present();
          modal.onDidDismiss(pointsSelected => { this.pointsSelected = pointsSelected}
          );
      }

      //错误原因
      doMultiChoice(){

        let alert = this.alertCtrl.create();
        alert.setTitle('错误原因');
        alert.addInput({
          type: 'checkbox',
          label: '计算错误',
          value: '计算错误',
          checked: true
        });
        alert.addInput({
            type: 'checkbox',
            label: '题目看错',
            value: '题目看错',
          });
        alert.addInput({
            type: 'checkbox',
            label: '掌握不牢固',
            value: '掌握不牢固',
          });
        alert.addInput({
          type: 'checkbox',
          label: '理解错误',
          value: '理解错误',
        });

        alert.addButton('Cancel');
        alert.addButton({
          text: '确定',
          handler: data => {
            this.testCheckboxOpen = false;
            this.testCheckboxResult = data;
            console.log(this.testCheckboxResult);
            this.testCheckboxResult.forEach(element => {
              console.log(element.value)
            });
          }
        });
        alert.present();
        this.editFlag = true;

      }

      //掌握程度
      checkStar(i){

        this.focus = i + 1;
        for(let j = 0;j < i + 1; j++){
          this.starList[j] = this.blingStarPath;
        }
        for(let j = i + 1;j<this.starList.length;j++){
          this.starList[j] = this.darkStarPath;
        }

      }

      submitMistakes(){
         this.mistake1 = new Mistake(this.id,null,"","","",'',"","","","","","","","");
         this.mistake1.misId = this.id;
         this.mistake1.username = this.username;
         if(this.quesPiclist.length > 0){
          this.mistake1.quesPicUrl = this.quesPiclist[0].path;
        }
        if(this.answerPiclist.length > 0){
          this.mistake1.answPicUrl = this.answerPiclist[0].path;
        }
         if (this.testCheckboxResult == "" || this.testCheckboxResult == null || this.testCheckboxResult == []) {
          this.mistake1.reason = "";
         }else{
           this.mistake1.reason = this.testCheckboxResult.join(",");
         }
         this.mistake1.masterDegree = this.focus;
         this.mistake1.bulidTime =  this.getDateTime()+"";
         this.mistake1.editTime = this.getDateTime()+"";
         this.mistake1.course = this.subject;

         this.mistake1.source=this.source;
         if(this.pointsSelected == "" || this.pointsSelected == null || this.pointsSelected == []) {
           this.mistake1.points = "";
         } else{
           this.mistake1.points = this.pointsSelected.join(",");
         }
         if(this.hasChooseQuestion){
           this.mistake1.sourceId = this.substituteQuestionChosen.id;
           this.mistake1.content = this.substituteQuestionChosen.title;
           console.log(this.mistake1.content);
         }

         console.log("id"+this.mistake1.misId);
         console.log("points"+this.mistake1.points);
         console.log("reason"+this.mistake1.reason);
         /*let loading = this.loadingCtrl.create({
           spinner:'hide',
           content:'Submitting Please Wait...'
         });
         loading.present();
         setTimeout(()=>{
          this.navCtrl.push(QuestionSetPage, { })
         },1000)
         */
         this.mistakeService.submitMistakes(this.mistake1).then(data=>
          {
            /*console.log("success callback recall");
            var callback = this.navparams.get("callback");
            callback(this.mistake1).then(()=>{
              console.log("返回页面");
              this.navCtrl.pop();
          });*/
            this.navCtrl.pop().then(()=>{
              this.event.publish('back',this.mistake1);
            })

        },
          error=>console.log(error));
          /*this.navCtrl.push(QuestionSetPage, {

        })*/
      }



      //上传问题图片
      quesImgChange(event){
        let token_headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded','authorization':this.token});
        let options = new RequestOptions({ headers: token_headers });

        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;

        var self = this;
        var reader = new FileReader();
        var prev_img = <HTMLInputElement>document.getElementById("pickfiles");
        var photoFile =  prev_img.files[0];

        reader.onload = function(e){
          let img = new Image();
          img.src = this.result;
          var width = img.width;
          var height = img.height;
          console.log("width: "+width);
          var quality = 0.8;
          var count = 0;
          var canvas = document.createElement("canvas");
          var drawer = canvas.getContext("2d");

          console.log(img.src.length);

          self.quesPiclist.push({path:this.result,flag:true});
          self.mistakeService.uploadBase64(this.result).then(
             data=> (self.substituteQuesList = data,
              self.substituteButtonFlag = true,
              self.pictureOrText = "picture",
              console.log(self.substituteQuesList),
              console.log("finish searching")
            ),
            error=>console.log(error));

        }


        reader.readAsDataURL(photoFile);

      }


      //上传答案图片
      answerImgChange(event){
        var self = this;
        var reader = new FileReader();
        var prev_img = <HTMLInputElement>document.getElementById("pickfiles2");
        var photoFile =  prev_img.files[0];

        reader.onload = function(e){
          let img = new Image();
          img.src = this.result;
          var width = img.width;
          var height = img.height;
          var quality = 0.8;
          var count = 0;
          var canvas = document.createElement("canvas");
          var drawer = canvas.getContext("2d");
         // img.src = this.result;
          console.log(img.src.length);
          self.answerPiclist.push({path:this.result,flag:true});

        }
        reader.readAsDataURL(photoFile);
      }

      //choose to substitute

      toSubstitutePage(i:number){
        let modal2;
        if(i == 0){
          if(this.pictureOrText = "picture"){
            modal2 = this.modalCtrl.create(SubstituteQuestionPage,{

             substituteQuesList : this.substituteQuesList.questionList
           });
        }

      }else if(i == 1){
          this.pictureOrText = "text";
         modal2 = this.modalCtrl.create(SubstituteQuestionPage,{
          searchByTextFlag : true
      });
      }
        modal2.present();
        modal2.onDidDismiss(questionUid => {
          console.log("id: "+questionUid);
          if(questionUid !=""){

            //上传图片查询和文字查询返回的结果不一样所以才写了两个
            /*if(this.pictureOrText="picture"){
              this.substituteQuestionChosen = (this.substituteQuesList.questionList)[questionUid];
              //this.tempPoint =  (this.substituteQuesList.knowledgePointList[0].knowledgePointContent);
              //this.tempPointList = this.substituteQuesList.knowledgePointList;
              //console.log("substituteQuesChosen: " + this.substituteQuestionChosen);
              //console.log("tempPoint: "+this.tempPoint);
            }else{
              this.substituteQuestionChosen = (this.substituteQuesList.questionList)[questionUid];
              //this.tempPoint =  (this.substituteQuestionChosen.knowledgePointList.knowledgePointContent);
              //this.tempPointList = this.substituteQuesList.knowledgePointList.knowledgePointContent;
              //console.log("substituteQuesChosen: " + this.substituteQuestionChosen);
              //console.log("tempPoint: "+this.tempPoint);
            }*/
            //选择题目后，保存questionUid，根据uid查询题目返回Question类
            //根据题目信息，查询知识点
            //错误原因
            this.mistakeService.getQuestionById(questionUid).then(question=>{
              this.substituteQuestionChosen = question,
                console.log(this.substituteQuestionChosen),
                this.hasChooseQuestion = true,
                console.log(this.hasChooseQuestion)
              this.source = this.substituteQuestionChosen.source
            });

            //this.quesPiclist[i].flag = false;
            this.substituteFlag = true;
            this.substituteButtonFlag = true;
            this.quesItemFlag = true;
            this.tempPointFlag = true;



          }else{
            this.substituteFlag = false;
          }
         // this.substituteQuestionChosen = this.substituteQuesList[questionUid]}
        }

      );
      }

       //改变答案图片大小
       changeImgSize(name){
        var image = <HTMLImageElement>document.getElementById("image_i");
        //console.log(image.width);
        if(this.imgflag == 1){
          image.width = 400;
          this.imgflag = 0;
        }else{
          image.width = 100;
          this.imgflag = 1;
        }
      }

      //改变问题图片大小
      changePicImgSize(name){
        var image = <HTMLImageElement>document.getElementById("quesImage_i");
       // console.log(image.width);
        if(this.picImgFlag == 1){
          image.width = 400;
          this.picImgFlag = 0;
        }else{
          image.width = 100;
          this.picImgFlag = 1;
        }

      }

     /* getMistakesByPoint(){
        var url = "http://localhost:8080/mistake/getMistakesByPoint?currentPoint="+this.currentPoint;
        console.log(url);
        return this.mistakeService.getMistakesByPoints(url).then(mistakeList=>this.mistakeListByPoints = mistakeList);
      }*/
      gotoSameExample(){
        this.navCtrl.push(SameExamplePage,{

        })
      }

      return(){
          this.navCtrl.push(QuestionSetPage,{

          })
      }

      // 格式化日期，获取今天的日期
      getDate() {
        const Dates = new Date();
        const year: number = Dates.getFullYear();
        const month: any = ( Dates.getMonth() + 1 ) < 10 ? '0' + ( Dates.getMonth() + 1 ) : ( Dates.getMonth() + 1 );
        const day: any = Dates.getDate() < 10 ? '0' + Dates.getDate() : Dates.getDate();
        return year + '-' + month + '-' + day;
    }

  getDate2() {
    const Dates = new Date();
    const year: number = Dates.getFullYear();
    const month: any = ( Dates.getMonth() + 1 ) < 10 ? '0' + ( Dates.getMonth() + 1 ) : ( Dates.getMonth() + 1 );
    const day: any = Dates.getDate() < 10 ? '0' + Dates.getDate() : Dates.getDate();
    const time:any = Dates.getHours()+''+Dates.getMinutes();
    return year + month + day + time;
  }
  getDateTime() {
    const Dates = new Date();
    const year: number = Dates.getFullYear();
    const month: any = ( Dates.getMonth() + 1 ) < 10 ? '0' + ( Dates.getMonth() + 1 ) : ( Dates.getMonth() + 1 );
    const day: any = Dates.getDate() < 10 ? '0' + Dates.getDate() : Dates.getDate();
    const time:any = Dates.getHours()+ ':' +Dates.getMinutes() + ':' +Dates.getSeconds();
    return year + '-'+ month + '-' + day + '-' + time;
  }


  }
